/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.bs.coregamelibrary.watcher;

import java.io.FileInputStream;
import java.io.InterruptedIOException;
import java.util.Properties;

/**
 *
 * @author ldtan
 */
public class PropertiesWatcher extends FileWatchDog {

    private Properties props;

    public PropertiesWatcher(String filename) {
        super(filename);
    }

    public PropertiesWatcher(String filename, long deplay) {
        super(filename);
        setDelay(delay);
    }

    @Override
    protected void doOnChange() {
        if (props == null) {
            props = new Properties();
        } else {
            props.clear();
        }
        FileInputStream istream = null;
        try {
            istream = new FileInputStream(this.filename);
            props.load(istream);
            istream.close();
        } catch (Exception e) {
            if (e instanceof InterruptedIOException || e instanceof InterruptedException) {
                Thread.currentThread().interrupt();
            }
            return;
        } finally {
            if (istream != null) {
                try {
                    istream.close();
                } catch (InterruptedIOException ignore) {
                    Thread.currentThread().interrupt();
                } catch (Throwable ignore) {
                }

            }
        }
    }

    public String getString(String key) {
        return this.props.getProperty(key, "");
    }

    public int getInt(String key) {
        String value = getString(key);
        try {
            return Integer.valueOf(value);
        } catch (Exception e) {
            return Integer.MIN_VALUE;
        }
    }


    public long getLong(String key) {
        String value = getString(key);
        try {
            return Long.valueOf(value);
        } catch (Exception e) {
            return Long.MIN_VALUE;
        }
    }

    public float getFloat(String key) {
        String value = getString(key);
        try {
            return Float.valueOf(value);
        } catch (Exception e) {
            return Float.MIN_VALUE;
        }
    }

    public double getDouble(String key) {
        String value = getString(key);
        try {
            return Double.valueOf(value);
        } catch (Exception e) {
            return Double.MIN_VALUE;
        }
    }

    public boolean getBool(String key) {
        String value = getString(key);
        try {
            return Boolean.valueOf(value);
        } catch (Exception e) {
            return Boolean.FALSE;
        }
    }

}
